﻿using System.IO;
using System.Web.Mvc;

namespace DuocThaiBinh.Common
{
    /// <summary>
    /// Custom file result to return excel file from memmory stream object.
    /// </summary>
    public class ExcelResult : ActionResult
    {
        public string FileName { get; set; }
        public MemoryStream Stream { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            var content = new byte[(int)Stream.Length];
            Stream.Read(content, 0, (int)Stream.Length);

            context.HttpContext.Response.Buffer = true;
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
            context.HttpContext.Response.AddHeader("Set-Cookie", "fileDownload=true; path=/");
            context.HttpContext.Response.ContentType = "application/octet-stream";
            context.HttpContext.Response.BinaryWrite(content);
            context.HttpContext.Response.Flush();
            context.HttpContext.Response.End();
            Stream.Flush();
            Stream.Close();
            Stream.Dispose();
        }
    }
}